<?php
namespace Home\Controller;
use Think\ControllerEx;
class OrderController extends CommonController {

    public function _initialize(){
        $goodsRes = R('Goods/getGoods',array('0'));
        $this->goodsRes = $goodsRes;

        $this->base_init(null);
    }
    
    //加载 耗材列表 页面
    public function upGoods(){
        $goodsRes =  R('Goods/getGoods',array('1'));
        $orderRes =  $this->isOrder();
        $this->assign('goodsList',$goodsRes);
        
        //没有上报加载 上报页面
        if ($orderRes) {
            //已上报 加载 当月上报 订单信息
            $this->assign('order',$orderRes);
            $this->display('isup');
        }else{

            $this->display('upGoods');
        }
    }

    /**
     * 查看 本月是否已上报
     * 已上报 返回  订单号 oid 及订单状态 status
     * 没有上报返回 false
     */
    public function isOrder($uid = '0'){
        if ($uid == '0') {
            $uid = session('home')['uid'];
        }
        
        $where['uid'] = $uid;
        $where['ym']  = date('Ym',time());
        $orderTab = M('Order');
        $orderRes = $orderTab->where($where)->field('oid,datetime,ym,status,comm')->find();
        //查到订单信息 返回 订单 
        if ($orderRes) {
            $date = $this->viewOrde($orderRes['oid']);
            $orderRes['goodsList'] = $date['goodsList'];
            $orderRes['totalAll'] = $date['totalAll'];
            if(IS_AJAX){
                $this->ajaxReturn($orderRes);
            }
            return $orderRes;
        }else{
            //没有查到信息 返回 false 
            if(IS_AJAX){
                $this->ajaxReturn(false);
            }
            return false;
        }
    }

    //上报耗材 
    public function doUpbao(){
        //已过21号不能上报
        if (date('d',time()) >= 21 ) {
            $this->error('已过21日不能上报！');
        }

        $date = I('post.');   //获取提交 的入库信息
        $uid  = $date['uid'];
        
        if (empty($uid)) {
            $uid = session('home')['uid'];
        }
        
        //删除 入库数为零的 耗材
        for ($i=0; $i < count($date['num']); $i++) { 
            if (!empty($date['num'][$i])) {
                    $goodsUp[] = array('gid'=>$date['gid'][$i],'num'=>$date['num'][$i]);
                } 
        }

        if ($date['oid'] == null ) {
            $oid = $this->createOid($uid,$date['comm']);
        }else{
            $oid = $date['oid'];
            //删除 所有原订单详情
            $this->delOrdetails($oid);  

            //修改订单 comm
            $orderTab = M('Order');
            $orderTab->comm = $date['comm'];
            $orderTab->where('oid='.$oid)->save();
        }

        //实例化 订单详情表
        $order_detailsTab = M('Order_details');

        for ($i=0; $i < count($goodsUp); $i++) {
            //获取 耗材最新的信息
            $goodsRes         = R('Goods/getRes',array($goodsUp[$i]['gid']));
            $newDate['oid']   = $oid;
            $newDate['gid']   = $goodsUp[$i]['gid'];
            $newDate['num']   = $goodsUp[$i]['num'];

            $newDate['price'] = $goodsRes['price'];
            $newDate['total'] = $goodsRes['price']*$goodsUp[$i]['num']; //单品总价
            //dump($newDate); 
            //记录订单详情 
            $odid[] = $order_detailsTab->add($newDate);
        }
        if ($odid) {
            R('User/upReport',array($uid));
            //判断是否代上报
            if (empty($date['uid'])) {
                $this->success('上报成功','upGoods','2');
            }else{
                //代上报跳转
                $this->redirect('/Admin/Order/daiUp',4, '上报成功！');
            }
        }
    }

    //生成新订单 oid
    public function createOid($uid = '0',$comm){

        $orderDate['uid']        = $uid;
        $orderDate['branchname'] = $user['branchname'];

        $orderDate['type']       = '0';  //类型0 为 上报耗材
        $orderDate['ym']         = date('Ym');
        $orderDate['datetime']   = time();  
        $orderDate['comm']       = $comm;

        //实例化 订单表
        $orderTab = M('Order');
        //生成订单
        $oid = $orderTab->add($orderDate);
        if ($oid) {
            return $oid;   //返回 最新订单 oid
        }else{
            $this->error('订单生成失败');
        }
    }

    //删除旧订单
    public function delOrdetails($oid){
        //实例化 订单详情表
        $order_detailsTab = M('Order_details');
        $where['oid'] = $oid;
        $orderRes = $order_detailsTab->where($where)->delete();
        if ($orderRes) {
            return true;
        }else{
            return false;
        }
    }


    /**
     * 查寻 登录 用户所有订单
     * $role 1,0,admin 为管理员，home 为普通用户 
     * 返回 array()
     */
    public function selOrder($uid = '0'){
        $time1  = I('time1');
        $time2  = I('time2');
        $time   = array('time1' =>$time1,'time2'=>$time2 );
        
        $where['uid'] = $uid;
        if (!empty($time1)  && !empty($time2)) {
            
            if ($time2 > $time1) {
                $where['ym']  = array(array('EGT',$time1),array('ELT',$time2));
            }else{
                $where['ym']  = array(array('ELT',$time1),array('EGT',$time2));
            }
        }
        
        $orderTab = M("Order");
        $count    = $orderTab->where($where)
                             ->field('oid,status,datetime,ym')
                             ->order('ym')
                             ->count();
        //实例化分页类
        $Page     = new \Think\Page($count,10);

        foreach($where as $key=>$val) {
            $Page->parameter[$key] = $val;  
            //$Page->parameter .= "&$key=".urlencode($val);
        }
        //查出 所有上报订单
        $orderRes = $orderTab->where($where)
                             ->field('oid,status,datetime,ym')
                             ->order('ym')
                             ->limit($Page->firstRow.','.$Page->listRows)
                             ->select();
        //echo $orderTab->getLastsql();
        $page       = $Page->show();
        //查询所有耗材信息
        $goodsRes = $this->goodsRes;  

        //循环 订单
        for ($i=0; $i < count($orderRes); $i++) {

            $goodsList[$i] = R('OrderDet/getOrderlist',array($orderRes[$i]['oid']));

            //将订单 所有的 gid 放入 一个新数组
            $gidList[$i] = array_keys($goodsList[$i]);
              
            //循环商品列表
            for ($g=0; $g < count($goodsRes); $g++) { 

                //如果 商品 耗材订单详情表中
                if (in_array($goodsRes[$g]['gid'], $gidList[$i])) {
                    $orderRes[$i]['goodsList'][] = $goodsList[$i][$goodsRes[$g]['gid']];
                }else{
                    $orderRes[$i]['goodsList'][] = array('gid'=>$goodsRes[$g]['gid'],'price'=>'','num'=>'','total'=>'');
                }
            } 

            $goodsList[$i]['total']   = array_column($goodsList[$i],'total');
            $orderRes[$i]['totalAll'] = array_sum($goodsList[$i]['total']);

        }
        $date = array('goodsList' => $goodsRes ,'orderList'=>$orderRes,'page'=>$page,'time'=>$time);
        return $date;
    }
    
    //查看 加载数据
    public function viewOrder($uid){
        //dump($uid);
        switch ($uid) {
            case 'home':
                $uid  = session('home')['uid'];
                $make = '上报';
                break;
            case 'admin':
                $uid  = session('admin')['uid'];
                $make = '入库';
                break;
            default:
                $uid  = $uid;
                $make = '上报';
                break;
        }
        //dump($uid);
        $date = $this->selOrder($uid);

        $this->assign('make',$make);
        $this->assign('time',$date['time']);
        $this->assign('page',$date['page']);  //分页
        $this->assign('goodsList',$date['goodsList']);
        $this->assign('orderList',$date['orderList']);

        $this->display('order_list');
    }

    //根据 订单号 查看订单详情 
    private function viewOrde($oid = 0){
       
        $goodsList = R('OrderDet/getOrderlist',array($oid));
        
        //将订单 所有的 gid 放入 一个新数组
        $gidList = array_keys($goodsList);
        $goodsRes = $this->goodsRes;
        
        //循环商品列表
        for ($g=0; $g < count($goodsRes); $g++) { 
            //如果 商品 耗材订单详情表中
            if (in_array($goodsRes[$g]['gid'], $gidList)) {    
                $orderRes['goodsList'][] = $goodsList[$goodsRes[$g]['gid']];
            }else{
                $orderRes['goodsList'][] = array('gid'=>$goodsRes[$g]['gid'],'price'=>'','num'=>'','total'=>'');
            }
        } 
        $goodsList['total'] = array_column($goodsList,'total');
        $orderRes['totalAll'] = array_sum($goodsList['total']);
        
        return $orderRes;  
    }


    public function create_xls(){

        $Res = $this->viewOrder();

        $goodsname = array();
        for ($i=0; $i < count($Res['goodsList']); $i++) { 
            $goodsname[$i] = $Res['goodsList'][$i]['goodsname']; 

        }
        array_unshift($goodsname,'上报时间','耗材名称'); 
        array_push($goodsname, '总计');

        $orderList = array();

        for ($o=0; $o <count($Res['orderList']) ; $o++) {
                $orderList[$o][0] = $Res['orderList'][$o]['ym'];
                $orderList[$o][1] = '';
            for ($j=0; $j < count($Res['orderList'][$o]['goodsList']); $j++) {
                $orderList[$o][$j+2] = $Res['orderList'][$o]['goodsList'][$j]['num'];  
            }
               $orderList[$o][] = $Res['orderList'][$o]['totalAll'];
        }

        $tit = $_SESSION['home']['branchname'].' 耗材上报领用一览';
        
        //dump($orderList);die;
        //dump($Res);die;
        exportExcel($tit,$goodsname, $orderList, '耗材领用表');
    }
}